package gui;

import config.*;
import exception.MyException;
import util.GameUtil;

import javax.swing.*;
import java.awt.*;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyFrame2 extends JFrame {
    private final static int WIDTH = 400;
    private final static int HEIGHT = 600;
    private static JFrame frame;
    //首页,不变
    private final static JPanel firstPage = new JPanel();
    //基本信息,每天变,交易物品变
    private final static JPanel top = new JPanel();
    //中间菜单,不变
    private final static JPanel center = new JPanel();
    //下层城市,每天变
    private final static JPanel down = new JPanel();
    //商品,每天变,每次购买或者出售的时候变
    private final static JPanel market = new JPanel();

    public MyFrame2() throws HeadlessException {
        frame = this;
        //获得屏幕尺寸
        Dimension windowSize = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLayout(new BorderLayout());
        frame.setBounds((int) windowSize.getWidth() / 2 - 200, (int) windowSize.getHeight() / 2 - 300, WIDTH, HEIGHT);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setVisible(true);
    }

    private void getFirstPage() {
        firstPage.setPreferredSize(new Dimension(300, 200));
        JButton button = new JButton("开始游戏");
        button.setPreferredSize(new Dimension(120, 60));
        button.addActionListener(event -> {
            //初始化,要求输入姓名和余额
            String name;
            while (true) {
                name = JOptionPane.showInputDialog("请输入用户名");
                if (name == null || name.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "名字为0-6个字符");
                    continue;
                }

                String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(name);
                if (m.find()) {
                    JOptionPane.showMessageDialog(this, "名字不能含有特殊字符");
                    continue;
                }
                break;
            }

            BigDecimal money;
            while (true) {
                String moneyString = JOptionPane.showInputDialog("请输入初始余额(整数)");
                try {
                    money = new BigDecimal(moneyString);
                    if (money.floatValue() < 0) {
                        throw new MyException("金钱不能为负数");
                    } else if (money.floatValue() % 1 != 0) {
                        throw new MyException("请输入整数");
                    }
                    break;
                } catch (MyException myException) {
                    JOptionPane.showMessageDialog(this, myException.getMessage());
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this, "请输入有效数字");
                }
            }
            People.setMoney(money);
            People.setName(name);
            System.out.println("名字:" + People.getName() + "余额:" + People.getMoney());
            //初始化商品
            Commodity.randCommodity();
            //初始化选项
            Options.init();
            //初始化城市
            City.init();
            GameUtil.setCity(City.CITES.get(0));
            //初始化游戏天数
            GameUtil.setDay(1);
            firstPage.setVisible(false);

            frame.add(getTop(), BorderLayout.NORTH);
            frame.add(getCenter(), BorderLayout.CENTER);
            frame.add(getDown(), BorderLayout.SOUTH);
            down.setVisible(false);
            frame.repaint();
            frame.revalidate();
        });
        firstPage.add(button);
    }

    private static JPanel getTop() {
        top.removeAll();
        top.setPreferredSize(new Dimension(400, 30));
        JLabel label1 = new JLabel("玩家:" + People.getName());
        JLabel label2 = new JLabel("金钱:" + People.getMoney());
        JLabel label3 = new JLabel("城市:" + GameUtil.getCity());
        JLabel label4 = new JLabel("天数:" + GameUtil.getDay());
        label1.setPreferredSize(new Dimension(90, 30));
        label2.setPreferredSize(new Dimension(90, 30));
        label3.setPreferredSize(new Dimension(90, 30));
        label4.setPreferredSize(new Dimension(90, 30));
        top.add(label1);
        top.add(label2);
        top.add(label3);
        top.add(label4);
        return top;
    }

    private static JPanel getCenter() {
        center.removeAll();
        center.setPreferredSize(new Dimension(400, 360));
        JButton button1 = new JButton("进入市场");
        JButton button2 = new JButton("原地休息");
        JButton button3 = new JButton("去其他城市");
        button1.setPreferredSize(new Dimension(300, 120));
        button2.setPreferredSize(new Dimension(300, 120));
        button3.setPreferredSize(new Dimension(300, 120));

        //设置三个按钮的监听事件
        button1.addActionListener(event -> {
            //进入市场--显示商品--弹窗买卖--输入数量--结算
            if (down.isVisible()) {
                down.setVisible(false);
            }
//            center.setVisible(false);
            frame.remove(center);
            frame.add(getMarket(), BorderLayout.CENTER);
            frame.repaint();
            frame.revalidate();
//            frame.setVisible(false);
//            frame.setVisible(true);
        });
        button2.addActionListener(event -> {
            //原地休息
            if (down.isVisible()) {
                down.setVisible(false);
            }
            GameUtil.nextDay();
            //刷新基本信息
            frame.add(getTop(), BorderLayout.NORTH);
            frame.repaint();
            frame.revalidate();

//            frame.setVisible(false);
//            frame.setVisible(true);
        });
        button3.addActionListener(event -> {
//            frame.setVisible(false);
            //去其他城市--显示可以去的城市
            down.setVisible(!down.isVisible());
            frame.repaint();
            frame.revalidate();
            //解决城市不显示问题
//            frame.setVisible(true);
        });

        center.add(button1);
        center.add(button2);
        center.add(button3);
        return center;
    }

    private static JPanel getDown() {
        down.removeAll();
        down.setPreferredSize(new Dimension(400, 90));

        for (String city : City.CITES) {
            if (!city.equals(GameUtil.getCity())) {
                JButton jButton = new JButton(city);

                jButton.addActionListener(event -> {
                    String text = event.getActionCommand();
                    GameUtil.setCity(text);
                    Commodity.randCommodity();
                    GameUtil.nextDay();
                    //不再显示城市列表
                    down.setVisible(false);
                    //更新城市列表
                    getDown();
                    //刷新基本信息
                    frame.add(getTop(), BorderLayout.NORTH);
                    frame.repaint();
                    frame.revalidate();
                });
                down.add(jButton);
            }
        }
        JButton button = new JButton("取消");
        button.addActionListener(event -> {
            frame.add(center, BorderLayout.CENTER);
            frame.repaint();
            frame.revalidate();
        });
        down.add(button);
        return down;
    }

    private static JPanel getMarket() {
        market.removeAll();
        market.setPreferredSize(new Dimension(400, 90));

        Commodity.COMMODITY.forEach((key, value) -> {
            String text = String.format("%4s%10s%10s\n", key, value.getCurrentPrice(), Backpack.COMMODITY.get(key) == null ? 0 : Backpack.COMMODITY.get(key));
            JButton button = new JButton(text);
            button.setPreferredSize(new Dimension(180, 30));

            button.addActionListener(event -> {
                //todo 购买/出售 -> 数量 -> 结算
                System.out.println(key);
                JDialog dialog = new JDialog(frame, key, true);
                dialog.setLocation(frame.getLocation(new Point(WIDTH / 2, HEIGHT / 2)));
//                dialog.setSize(110,220);
                dialog.setLayout(new BorderLayout());

                JPanel option = new JPanel();

                JButton buy = new JButton("购买");
                JButton sell = new JButton("出售");
                JButton cancel = new JButton("取消");
//                buy.setPreferredSize(new Dimension(100,50));
//                sell.setPreferredSize(new Dimension(100,50));
//                cancel.setPreferredSize(new Dimension(100,50));
                buy.addActionListener(event2 -> {
                    //todo 购买
                    System.out.println("购买");
                    dialog.dispose();
                    String num = (int) (People.getMoney().floatValue() / value.getCurrentPrice().floatValue()) + "";
                    int i;
                    while (true) {
                        String input = JOptionPane.showInputDialog(market, "请输入数量", num);
                        if (input == null) {
                            return;
                        }
                        System.out.println(input);
                        try {
                            BigDecimal bigDecimal = new BigDecimal(input);
                            i = bigDecimal.intValue();
                            if (i <= 0) {
                                throw new MyException("数量必须大于0");
                            }
                            if (i > Integer.parseInt(num)) {
                                throw new MyException("你没有足够的钱");
                            }
                            break;
                        } catch (MyException e) {
                            JOptionPane.showMessageDialog(null, e.getMessage(), "错误 ", 0);
                        } catch (Exception e2) {
                            JOptionPane.showMessageDialog(null, "请输入正整数", "错误 ", 0);
                        }
                    }

                    //        扣钱,将商品放入背包
                    BigDecimal multiply = value.getCurrentPrice().multiply(new BigDecimal(i));
                    People.setMoney(People.getMoney().subtract(multiply));
                    Backpack.COMMODITY.put(key, i);

                    //更新市场
                    getMarket();
                    getTop();
                    frame.repaint();
                    frame.revalidate();
                });
                sell.addActionListener(event2 -> {
                    //todo 出售
                    System.out.println("出售");
                    dialog.dispose();
                    Integer num = Backpack.COMMODITY.get(key);
                    if (num == null || num == 0) {
                        JOptionPane.showMessageDialog(null, "您的背包中没有此商品", "错误 ", 0);
                        return;
                    }
                    int i;
                    while (true) {
                        String input = JOptionPane.showInputDialog(market, "请输入数量", num);
                        if (input == null) {
                            return;
                        }
                        System.out.println(input);
                        try {
                            BigDecimal bigDecimal = new BigDecimal(input);
                            i = bigDecimal.intValue();
                            if (i <= 0) {
                                throw new MyException("数量必须大于0");
                            }
                            if (i > num) {
                                throw new MyException("你没有这么多此物品");
                            }
                            break;
                        } catch (MyException e) {
                            JOptionPane.showMessageDialog(null, e.getMessage(), "错误 ", 0);
                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(null, "请输入正整数", "错误 ", 0);
                        }
                    }

                    //加钱,将商品移出背包
                    BigDecimal multiply = value.getCurrentPrice().multiply(new BigDecimal(i));
                    People.setMoney(People.getMoney().add(multiply));
                    Backpack.COMMODITY.put(key, num - i);

                    //更新市场
                    getMarket();
                    getTop();
                    frame.repaint();
                    frame.revalidate();
                });
                cancel.addActionListener(e -> {
                    System.out.println("取消");
                    dialog.dispose();
                });
                option.add(buy);
                option.add(sell);
                option.add(cancel);

                dialog.add(option);
                dialog.pack();
                dialog.setVisible(true);
            });

            market.add(button);
        });
        JButton button = new JButton("返回");
        button.setPreferredSize(new Dimension(300, 60));
        button.addActionListener(event -> {
            frame.remove(market);
            frame.add(center, BorderLayout.CENTER);
            frame.repaint();
            frame.revalidate();
        });
        market.add(button);

        return market;
    }

    public void initGame() {
        //初始化界面,设置容器所在位置
        getFirstPage();
        getTop();
        getCenter();
        getDown();
        getMarket();

        top.setVisible(true);
        center.setVisible(true);
        down.setVisible(true);
        market.setVisible(true);

        //开始游戏
        frame.add(firstPage, BorderLayout.NORTH);
        //玩家...金钱....天数...城市
//        frame.add(top,BorderLayout.NORTH);
        //进入市场...原地休息...去其他城市
//        frame.add(center,BorderLayout.CENTER);
        //显示商品
//        frame.add(market,BorderLayout.CENTER);
        frame.repaint();
        frame.revalidate();
        System.out.println("游戏初始化完成");
    }

    public void startGame() {
        System.out.println("开始游戏");
        //显示开始游戏
//        firstPage.setVisible(true);
//        frame.setVisible(false);
//        frame.setVisible(true);
//        frame.repaint();
//        frame.revalidate();
    }

}
